﻿using System;
using System.Reflection;
using System.Windows.Forms;

namespace Macaw.SolutionsFactory.FactoryIdeTools.CCNetBuildStation
{
    public partial class FormAbout : Form
    {
        public FormAbout()
        {
            InitializeComponent();
        }

        private void FormAbout_Load(object sender, EventArgs e)
        {
            labelProduct.Text = GetAssemblyAttribute<AssemblyProductAttribute>();
            labelCopyright.Text = GetAssemblyAttribute<AssemblyCopyrightAttribute>();
            labelVersion.Text = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            labelDescription.Text = GetAssemblyAttribute<AssemblyDescriptionAttribute>();
        }

        /// <summary>
        /// Close the "About" window.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private static string GetAssemblyAttribute<T>() where T:Attribute
        {
            string retValue = String.Empty;

            string attributeName = typeof(T).Name;
            if (!attributeName.StartsWith("Assembly") || !attributeName.EndsWith("Attribute"))
            {
                throw new ArgumentException(string.Format("Type '{0}' is not valid. only Assembly[X]Attribute allowed.", typeof(T).ToString()));
            }

            Assembly assembly = Assembly.GetExecutingAssembly();

            object[] attributes = assembly.GetCustomAttributes(typeof(T), false);
            T attribute = default(T);
            if (attributes.Length > 0)
            {
                attribute = attributes[0] as T;

                if (attribute != null)
                {
                    // Parse the [X] from Assembly[X]Attribute
                    String propertyName =
                        attributeName.Remove(attributeName.Length - "Attribute".Length).Substring("Assembly".Length);

                    // Read the [X] as a property on the attribute using reflection
                    PropertyInfo property = attribute.GetType().GetProperty(propertyName);
                    if (property != null)
                    {
                        retValue = property.GetValue(attribute, null).ToString();
                    }
                }
            }

            return retValue;
        }

        private void linkLabelToCodeplex_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.codeplex.com/CCNetBuildStation");
        }
    }
}
